﻿using DotNet4.Utilities;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace BaiduYun
{
    internal class BaiduYunPan
    {
        public string Cookie { get; }
        public string Stoken { get; }

        public BaiduYunPan(string cookie)
        {
            this.Stoken = GetStoken(cookie);
            if (string.IsNullOrEmpty(this.Stoken)) throw new ArgumentException("Cookie无效");
            this.Cookie = cookie;
        }

        /// <summary>
        /// 通过cookie获取Stoken
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns>失败返回String.Empty</returns>
        private static string GetStoken(string cookie)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = "http://pan.baidu.com/disk/home#list/path=%2F",
                Cookie = cookie,
            };
            HttpResult res = http.GetHtml(item);
            Match m = Regex.Match(res.Html, "bdstoken\":\"(.*?)\"");
            if (!m.Success) return string.Empty;

            return m.Groups[1].Value;
        }

        public static bool IsCookieValid(string cookie) => !string.IsNullOrEmpty(GetStoken(cookie));

        public struct VideoInfo
        {
            public string url, path;

            public VideoInfo(string url, string path)
            {
                this.url = url;
                this.path = path;
            }
        }

        /// <summary>
        /// 获取被和谐视频路径
        /// </summary>
        /// <param name="page"></param>
        /// <returns>如果page 到末尾了，返回null</returns>
        public List<VideoInfo> GetVideoPath(int page)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = $"http://pan.baidu.com/api/categorylist?order=time&desc=1&showempty=0&web=1&page={page.ToString()}&num=100&category=1&t=0.11549030674903626&bdstoken={this.Stoken}&channel=chunlei&clienttype=0&web=1&app_id=250528&logid=",
                Cookie = this.Cookie,
            };
            HttpResult res = http.GetHtml(item);
            MatchCollection mc = Regex.Matches(res.Html, "icon\":\"(.*?)\".*?path\":\"(.*?)\"");
            Console.WriteLine(mc.Count);
            List<VideoInfo> list = new List<VideoInfo>();
            // 到达page末尾 返回null
            if (mc.Count == 0) return null;
            foreach (Match m in mc)
            {
                // 视频封面地址
                string url = m.Groups[1].Value.Replace("\\/", "/");
                // 视频路径
                string path = m.Groups[2].Value.Replace("\\/", "/");
                path = StringHelper.Decode(path);
                list.Add(new VideoInfo(url, path));
            }
            return list;
        }

        /// <summary>
        /// 图片是否是被屏蔽图片
        /// </summary>
        /// <param name="imgUrl"></param>
        /// <returns></returns>
        public static bool IsImgShield(string imgUrl)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = imgUrl,
                ResultType = ResultType.Byte,
            };

            HttpResult res = res = http.GetHtml(item);
            if (res.ResultByte.Length == 585) return true;
            return false;
        }

        public void DeleteFile(string[] path)
        {
            string filelist = "[";
            foreach (string p in path)
            {
                filelist += "\"" + p + "\",";
            }

            filelist = filelist.Substring(0, filelist.Length - 1) + "]";
            string logid = GetLogid();
            string postdata = "filelist=" + Uri.EscapeDataString(filelist);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = "http://pan.baidu.com/api/filemanager?opera=delete&async=2&bdstoken=4d22ee4d5a390dad32a8dba906fa4c2b&channel=chunlei&clienttype=0&web=1&app_id=250528&logid=" + logid,
                Method = "POST",
                Postdata = postdata,
                Cookie = Cookie,
            };
            HttpResult res = http.GetHtml(item);

            /** ERR     CODE
                    0: "成功",
        "-1": "用户名和密码验证失败",
        "-2": "备用",
        "-3": "用户未激活（调用init接口）",
        "-4": "COOKIE中未找到host_key&user_key（或BDUSS）",
        "-5": "host_key和user_key无效",
        "-6": "登录失败，请重新登录",
        "-7": "文件或目录名错误或无权访问",
        "-8": "该目录下已存在此文件",
        "-9": "文件被所有者删除，操作失败",
        "-10": a,
        "-11": "父目录不存在",
        "-12": "设备尚未注册",
        "-13": "设备已经被绑定",
        "-14": "帐号已经初始化",
        "-21": "预置文件无法进行相关操作",
        "-22": "被分享的文件无法重命名，移动等操作",
        "-23": "数据库操作失败，请联系netdisk管理员",
        "-24": "要取消的文件列表中含有不允许取消public的文件。",
        "-25": "非公测用户",
        "-26": "邀请码失效",
        "-102": "云冲印文件7日内无法删除",
        1: "服务器错误 ",
        2: "接口请求错误，请稍候重试",
        3: "一次操作文件不可超过100个",
        4: "新文件名错误",
        5: "目标目录非法",
        6: "备用",
        7: "NS非法或无权访问",
        8: "ID非法或无权访问",
        9: "申请key失败",
        10: "创建文件的superfile失败",
        11: "user_id(或user_name)非法或不存在",
        12: "部分文件已存在于目标文件夹中",
        13: "此目录无法共享",
        14: "系统错误",
        15: "操作失败",
        102: "无权限操作该目录",
        103: "提取码错误",
        104: "验证cookie无效",
        201: "系统错误",
        202: "系统错误",
        203: "系统错误",
        204: "系统错误",
        205: "系统错误",
        301: "其他请求出错",
        501: "获取的LIST格式非法",
        618: "请求curl返回失败",
        619: "pcs返回错误码",
        600: "json解析出错",
        601: "exception抛出异常",
        617: "getFilelist其他错误",
        211: "无权操作或被封禁",
        404: "秒传md5不匹配 rapidupload 错误码",
        406: "秒传创建文件失败 rapidupload 错误码",
        407: "fileModify接口返回错误，未返回requestid rapidupload 错误码",
        1024: "云冲印购物车文件15日内无法删除",
        31080: "我们的服务器出错了，稍候试试吧",
        31021: "网络连接失败，请检查网络或稍候再试",
        31075: "一次支持操作999个，减点试试吧",
        31116: '你的空间不足了哟，赶紧<a href="//yun.baidu.com/buy/center?tag=2&from=multi-file">购买空间</a>吧',
        112: '页面已过期，请<a href="javascript:window.location.reload();"">刷新</a>后重试',
        111: "当前还有未完成的任务，需完成后才能操作",
            **/
        }

        private static string GetLogid()
        {
            script_run.ScriptEngine myScript = new script_run.ScriptEngine(script_run.ScriptLanguage.JavaScript);
            object jsmethodRunValue = myScript.Run("main", new object[] { "BAIDUID=FBDA4A7839B977119EF51DC4275DA98E:FG=1" }, Resource1.Script);
            string logid = jsmethodRunValue.ToString();
            return logid;
        }
    }
}